//
//  PeiHuShiViewController.m
//  XiangMu
//
//  Created by  方崇豪 on 15/7/13.
//  Copyright (c) 2015年  方崇豪. All rights reserved.
//

#import "PeiHuShiViewController.h"
#import "Header.h"
#import "SVPullToRefresh.h"
#import "CCLocationManager.h"
@import CoreLocation;

@interface PeiHuShiViewController ()

@end

@implementation PeiHuShiViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    if (self.tabBarHidden == YES) {
          self.tabBarController.tabBar.hidden = YES;
    }
    else{
          self.tabBarController.tabBar.hidden = NO;
    }
  
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
  //
    [self GangJinLaiDeShuJu];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"dianchiliang"] forBarMetrics:UIBarMetricsDefault];
    
    _selectArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    self.navigationItem.title=@"陪护师";
    
    UIColor * color = [UIColor whiteColor];
    
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    
//    NSForegroundColorAttributeName
    self.navigationController.navigationBar.titleTextAttributes = dict;

    self.automaticallyAdjustsScrollViewInsets = NO;

    
    _datasArr = [[NSMutableArray alloc] initWithCapacity:0];
    
    [self QingQiuShuJU];
    [self jingWeiDu];
    [self showti:@"数据加载中" xuanZe:NO];
    self.tableView1.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 下拉刷新
    [self.tableView1 addPullToRefreshWithActionHandler:^
    {
        
        [self performSelector:@selector(xialaSuaXin) withObject:self afterDelay:1.5];
        
    }];
    //上推加载更多
    [self.tableView1 addInfiniteScrollingWithActionHandler:^{
        
        [self performSelector:@selector(JiaZaiGengDuo) withObject:self afterDelay:1];
    }];
    
    i=1;
    
  [self jsDOrop];
}
//菜单
- (void)jsDOrop{
    
    self.menuArr       = [NSMutableArray arrayWithObjects:@"价格",@"年龄",@"条件",@"状态",@"其他", nil];
    NSArray * picArr   = @[@"价格" ,@"0-100",@"100-200",@"200以上"];
    
    NSArray * ageArr   = @[@"年龄", @"30-40",@"40-50-40",@"51以上"];
    
    NSArray * sexArr   = @[@"年龄",@"男",@"女"];
    
    NSArray * condArr  = @[@"状态",@"闲",@"忙",];
    
    NSArray * otherArr = @[@"其他",@"距离最近", @"护龄最长",@"好评优先"];
    
    self.bigArr        = [NSArray arrayWithObjects:picArr,ageArr,sexArr,condArr,otherArr ,nil];
    
    
    JSDropDownMenu * menu = [[JSDropDownMenu alloc]initWithOrigin:CGPointMake(0, 40) andHeight:30];
    

    menu.delegate = self;
    
    menu.dataSource = self ;
    menu.indicatorColor = [UIColor colorWithRed:175.0f/255.0f green:175.0f/255.0f blue:175.0f/255.0f alpha:1.0];
    menu.separatorColor = [UIColor colorWithRed:210.0f/255.0f green:210.0f/255.0f blue:210.0f/255.0f alpha:0];
    menu.textColor = [UIColor colorWithRed:83.f/255.0f green:83.f/255.0f blue:83.f/255.0f alpha:1.0f];
    
    [self.view addSubview:menu];
    
}
#pragma  mark -- JSDropDownMenuDelegate
- (void)menu:(JSDropDownMenu *)menu didSelectRowAtIndexPath:(JSIndexPath *)indexPat
{
    switch (indexPat.column) {
        case 0:
        {
            self.currentData1Index =indexPat.row;
            [_dic setObject:@(indexPat.row) forKey:@"price"];
            
        }
            break;
        case 1:
        {
            self.currentData2Index =indexPat.row;
            [_dic setObject:@(indexPat.row) forKey:@"age"];

        }
            break;
        case 2:
        {
            self.currentData3Index =indexPat.row;
            [_dic setObject:@(indexPat.row) forKey:@"sex"];

        }
            break;
        case 3:
        {
            self.currentData4Index =indexPat.row;
            [_dic setObject:@(indexPat.row) forKey:@"state"];

        }
            break;
        case 4:
        {
            self.currentData5Index =indexPat.row;
            if (indexPat.row==0)
            {
                [self.dic setObject:@(-1) forKey:@"lng"];
                [self.dic setObject:@(-1) forKey:@"lat"];
                [self.dic setObject:@(-1) forKey:@"other"];
            }
            else if (indexPat.row==1){
                [self.dic setObject:@(_longitude) forKey:@"lng"];
                [self.dic setObject:@(_latitude) forKey:@"lat"];
                [self.dic setObject:@(indexPat.row) forKey:@"other"];
            }
            else
            {
                [self.dic setObject:@(-1) forKey:@"lng"];
                [self.dic setObject:@(-1) forKey:@"lat"];
                [self.dic setObject:@(indexPat.row) forKey:@"other"];
            }

        }
            break;

        default:
            break;
    }
    [self.dic setObject:@(1) forKey:@"page"];
     i=1;
    [_datasArr removeAllObjects];
    [self showti:@"数据加载中" xuanZe:NO];
    [self QingQiuShuJU];
}
#pragma mark ---- JSDropDownMenuDataSource
- (NSInteger)menu:(JSDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column leftOrRight:(NSInteger)leftOrRight leftRow:(NSInteger)leftRow{
    
    return [[self.bigArr objectAtIndex:column] count];
    
}
- (NSString *)menu:(JSDropDownMenu *)menu titleForRowAtIndexPath:(JSIndexPath *)indexPath
{
    return [[self.bigArr objectAtIndex:indexPath.column] objectAtIndex:indexPath.row];
    
}
- (NSString *)menu:(JSDropDownMenu *)menu titleForColumn:(NSInteger)column{
    
    return  [self.menuArr objectAtIndex:column];
    
}
- (NSInteger)numberOfColumnsInMenu:(JSDropDownMenu *)menu{
    
    return self.menuArr.count;
}
/**
 * 表视图显示时，左边表显示比例
 */
- (CGFloat)widthRatioOfLeftColumn:(NSInteger)column{
    
    return 1;
    
}
/**
 * 表视图显示时，是否需要两个表显示
 */
- (BOOL)haveRightTableViewInColumn:(NSInteger)column{
 
    return NO;
}

/**
 * 返回当前菜单左边表选中行
 */
- (NSInteger)currentLeftSelectedRow:(NSInteger)column{
    
    switch (column) {
        case 0:
        {
            return self.currentData1Index;
        }
            break;
        case 1:
        {
            return self.currentData2Index;
        }
            break;
        case 2:
        {
            return self.currentData3Index;
        }
            break;
        case 3:
        {
            return self.currentData4Index;
        }
            break;
        case 4:
        {
            return self.currentData5Index;
        }
            break;

        default:
            break;
    }
    return 0;
    
}

//第一次进来加载默认数据
- (void)GangJinLaiDeShuJu{
     self.dic = [[NSMutableDictionary alloc]initWithCapacity:0];
    [self.dic setObject:@(0) forKey:@"carerType"];
    [self.dic setObject:@(0) forKey:@"weightType"];
    [self.dic setObject:@(0) forKey:@"price"];
    [self.dic setObject:@(0) forKey:@"age"];
    [self.dic setObject:@(0) forKey:@"sex"];
    [self.dic setObject:@(0) forKey:@"state"];
    [self.dic setObject:@(1) forKey:@"page"];
    [self.dic setObject:@(10) forKey:@"rows"];
    [self.dic setObject:@"杭州" forKey:@"city"];
    [self.dic setObject:@(-1) forKey:@"lng"];
    [self.dic setObject:@(-1) forKey:@"lat"];
    [self.dic setObject:@(-1) forKey:@"other"];
    [self.dic setObject:@(0) forKey:@"type"];

    if ([self.yiyuan isEqualToString:@"医院"])
    {
        [self.dic setObject:@(self.leiXingIndex) forKey:@"carerType"];
        [self.dic setObject:@(self.tiZhongIndex) forKey:@"weightType"];
        [self.dic setObject:@(1) forKey:@"type"];
    }
    else if ([self.yiyuan isEqualToString:@"老人"])
    {
        [self.dic setObject:@(self.leiXingIndex) forKey:@"carerType"];
        [self.dic setObject:@(self.tiZhongIndex) forKey:@"sex"];
        [self.dic setObject:@(2) forKey:@"type"];
    }
    else{
     
           }
}
 // 下拉刷新
- (void)xialaSuaXin{
   [_datasArr removeAllObjects];
    [self.dic setObject:@(1) forKey:@"page"];
    [self QingQiuShuJU];
    
}
 //上推加载更多
- (void)JiaZaiGengDuo{
   
    
    i++;
    if (i<=_msgPage)
    {
        
        [self.dic setObject:@(i) forKey:@"page"];
        
        [self QingQiuShuJU];

    }
    else{
        
        [self.tableView1.infiniteScrollingView stopAnimating];
        
        [self.tableView1.pullToRefreshView stopAnimating];
        
        hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        hud.mode=MBProgressHUDModeText;
        
        hud.labelText=@"没有更多数据了";
        
        hud.removeFromSuperViewOnHide=YES;
        
        [hud hide:YES afterDelay:1.5];

        
    }
  
}
-(void)showti:(NSString *)text xuanZe:(BOOL)isOk{
    
    hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
 
   
    hud.labelText=text;
    [hud show:YES];
    hud.removeFromSuperViewOnHide=YES;
}
//获取经纬度
- (void)jingWeiDu{
    [[CCLocationManager shareLocation ] getLocationCoordinate:^(CLLocationCoordinate2D locationCorrrdinate) {
        
        _longitude=locationCorrrdinate.longitude;
        _latitude = locationCorrrdinate.latitude;
        if (_latitude ==0||_longitude ==0) {
            
            [[[UIAlertView alloc]initWithTitle:nil message:@"定位失败" delegate:nil cancelButtonTitle:nil otherButtonTitles: @"取消",nil]show];
            return ;
        }

        [self.tableView1 reloadData];
    }];
}

-(void)QingQiuShuJU{
    
    [QingQiuShuJu HuoQuHongGong:self.dic HuGong:^(NSMutableArray *arr, BOOL isOK) {
        
     
        if (isOK)
        {
            if ([[arr valueForKey:@"status"] intValue]==200)
            {
                _msgPage=[[arr valueForKey:@"msg"] intValue];
                
                
                [_datasArr addObjectsFromArray:[arr valueForKey:@"data"]];
                
                [self.tableView1 reloadData];
                
                [hud hide:YES];
                 self.tableView1.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
                [self.tableView1.pullToRefreshView stopAnimating];
                [self.tableView1.infiniteScrollingView stopAnimating];
            }
            
            else{
                [self.tableView1.infiniteScrollingView stopAnimating];
                [self.tableView1.pullToRefreshView stopAnimating];
                [self.view addSubview:hud];
                hud.mode=MBProgressHUDModeText;
                hud.labelText=[arr valueForKey:@"msg"];
                hud.removeFromSuperViewOnHide=YES;
                [hud hide:YES afterDelay:1.5];
                
                [self.tableView1 reloadData];
            }
        }
        else
        {   [self.tableView1.infiniteScrollingView stopAnimating];
            [self.tableView1.pullToRefreshView stopAnimating];
            [hud hide:YES];
            hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
           
            hud.mode=MBProgressHUDModeText;
            hud.labelText=@"网络连接超时";
            hud.removeFromSuperViewOnHide=YES;
            [hud hide:YES afterDelay:1.5];
            
        }
        
    }];
}
#pragma mark ---UISearchBarDelegate
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    
    NSArray *subViews=[(self.scaechBar.subviews[0]) subviews];
    for (id view in subViews) {
     if ([view isKindOfClass:[UIButton class]]) {
        UIButton *cancelbutton=(UIButton *)view;
        [cancelbutton setTitle:@"取消" forState:UIControlStateNormal];
       
        
     }
        
    }
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
 
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    SongSuoViewController * s = [[SongSuoViewController alloc]init];
    s.context = searchBar.text;

    [self.navigationController pushViewController:s animated:YES];
    
}
#pragma mark---UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{


      return _datasArr.count;
 
  
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PeiHuShiTableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:@"peihushi"];
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"PeiHuShiTableViewCell" owner:nil options:nil]lastObject];
            
        }
        
    
        
        [cell shuJu:_datasArr index:indexPath.row lat:_latitude longitude:_longitude];
        [cell.collection addTarget:self action:@selector(shouCang:) forControlEvents:UIControlEventTouchUpInside];
        cell.collection.tag = indexPath.row;
        
        
        
        return cell;
        
 
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    判断有没有登陆
    if ([UserManager login])
    {
        
        DengLuViewController *d=[[DengLuViewController alloc]init];
        UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:d];
        
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        
        return;
    }
        NSDictionary * dic =_datasArr[indexPath.row];
        
        
        if ([[dic valueForKey:@"state"] intValue]==1)
        {
                        //闲
            XiaDanViewController * x = [[XiaDanViewController alloc]init];
            
            x.dic = _datasArr[indexPath.row];
            
            [self.navigationController pushViewController:x animated:YES]
            ;
             return;
        }
        else{
            
            [[[UIAlertView alloc]initWithTitle:nil message:@"当前陪护师正在陪护中" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil]show];
            
            return;
            
        }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.1f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 116;


}
//收藏
- (void)shouCang:(UIButton *)shou{
    
    hud= [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary * dic =[self.datasArr objectAtIndex:shou.tag];
    
      if ([UserManager login])
    {
        
        DengLuViewController *d=[[DengLuViewController alloc]init];
        UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:d];
        
        [self.navigationController presentViewController:nav animated:YES completion:nil];

        
    }
    
    long uesrId= [[[NSUserDefaults standardUserDefaults]objectForKey:@"ID"] longValue];
    
    
    [QingQiuShuJu AddPeiHuShiShouCang:@(uesrId) carerId:@([[dic valueForKey:@"id"] longValue]) block:^(NSDictionary *dic, BOOL isOK)
    {
        if (isOK)
        {
            hud.mode=MBProgressHUDModeText;
            
            hud.labelText = [dic valueForKey:@"msg"];
            hud.removeFromSuperViewOnHide= YES;
            [hud hide:YES afterDelay:1.5];
            
          
        }
        else{
            hud.mode=MBProgressHUDModeText;
            hud.labelText = @"网络连接错误";
            hud.removeFromSuperViewOnHide= YES;
            [hud hide:YES afterDelay:1.5];

        }
        
    }];
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
